import React, { useState, useEffect } from 'react'
import PropTypes from 'prop-types'
import { useHistory } from 'react-router-dom'
import { api2, getToken } from "../api.js"

import './routes.css'

const Reviews = (props) => {
  const [reviews, setReviews] = useState([])
  const history = useHistory()

  useEffect(() => {
    fetchReviews()
  }, [])

  const fetchReviews = async () => {
    try {
      const token = getToken()
      const response = await api2.send('getAllUserReviews', { token })
      if (response.success) {
        setReviews(response.data)
      } else {
        console.error('Failed to fetch reviews:', response.error)
      }
    } catch (error) {
      console.error('Error fetching reviews:', error)
    }
  }

  const handleReviewClick = (reviewId) => {
    history.push(`/review/${reviewId}`)
  }

  return (
      <div className="routes-container thq-section-padding">
        <div className="routes-max-width thq-section-max-width">
          <div className="routes-content thq-flex-column">
            <ul className="routes-ul thq-flex-column">
              {reviews.map((review) => (
                  <li key={review.id} className="thq-flex-column list-item routes-li">
                    <h2 className="routes-heading1 thq-heading-2">
                      {review.title}
                    </h2>
                    <p className="thq-body-small">
                      Rating: {review.rating} | Date: {review.rev_date}
                    </p>
                    <button
                        className="routes-button thq-button-outline"
                        onClick={() => handleReviewClick(review.id)}
                    >
                  <span className="thq-body-small">
                    <span>Подробнее</span>
                    <br></br>
                  </span>
                    </button>
                  </li>
              ))}
            </ul>
          </div>
        </div>
      </div>
  )
}

Reviews.propTypes = {
  // You can add any additional props here if needed
}

export default Reviews

/*Routes.defaultProps = {
  heading1: 'Название пути',
}

Routes.propTypes = {
  heading1: PropTypes.string,
}

export default Routes*/
